import router from '@/router'
import { ICommonState, IDictKeyV, IPageTab } from '@/typings'
import { TOGGLE_LOADING, SET_DICT_BY_KEY, SET_ROUTER, DEL_ROUTER } from './actionTypes'

export default {
  [TOGGLE_LOADING](state: ICommonState, loading: boolean): void {
    state.loading = loading
  },
  [SET_DICT_BY_KEY](state: ICommonState, payload: IDictKeyV): void {
    const { key, value } = payload
    const dictData = state.dictData
    dictData.set(key, value)
    state.dictData = dictData
  },
  [SET_ROUTER](state: ICommonState, payload: IPageTab): void {
    if (state.pageTabs.some((item) => item.key === payload.key)) return
    state.pageTabs.push(payload)
  },
  [DEL_ROUTER](state: ICommonState, key: string): void {
    const i = state.pageTabs.findIndex((item) => item.key === key)
    if (i !== -1) {
      state.pageTabs.splice(i, 1)
      router.push(i === 0 ? '/home' : state.pageTabs[i - 1].key)
    }
  }
}
